Python is a general purpose, high level language.python in the Command Prompt or Terminal. The output should look like➜ learnpythoninminutes python
Python 2.7.5 (default, Mar 9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
Command takes you to Python Interactive Shell. The important thing to note here is Python 2.7.5 which says python version installed in the machine. All the tutorial will focus on Python 2.7.x. >>> print("Welcome to learn python in minutes tutorial")
Welcome to learn python in minutes tutorial
>>> place = "Bangalore"
>>> duration = 180 # Duration in minutes. This is a comment!
>>> author = "Kracekumar"
>>> print("Welcome to learn python in minutes tutorial by %s for %d minutes in %s" % (author, duration, place))
Welcome to learn python in minutes tutorial by Kracekumar for 180 minutes in Bangalore
>>> indicates we are inside Python interpreter.place = "Bangalore" is variable. Left hand side of = is the name of the variable and right hand side is the value.print() is function which prints result to standard output, here it is Python Interpreter.duration = 180 is a variable which stores int value.%s, %d are format specifiers like C.Python has very good support for number crunching.>>> duration_in_mins = 180
>>> duration_in_mins / 60 # Hours, in int
3
>>> duration_in_mins / 60.0 # Hours, in float
3.0
>>> duration_in_mins * 60 # In seconds
10800
>>> 12 + 23 # Simple add
35
>>> 12 - 23 # Subtraction
-11
>>> 12 / 23 # Division
0
>>> 12 / 23.0 # Note the denominator
0.5217391304347826
>>> 12 * 23.0 # multiply
276.0
>>> 3 % 2 # Modulo
1
>>> 12 ** 23.0 # 12 power of 23
6.624737266949237e+24 # When number is too large scientif notation is used
>>> 12 ** 12
8916100448256
>>> 12 ** 18
26623333280885243904L # `L` at the end says it is a long number.
>>> 12 + 20 * 2 - 4 * 2 / 2.0
48.0
>>> 12 + (20 * 2) - 4 * (2 / 2.0)
48.0
>>> 12 + (20 * 2) - (4 * 2 ) / 2.0
48.0
int result will be int else float.Let's see how expression are handled without brackets.
12 + 20 * 2 - 4 * 2 / 2.0
12 + 40 - 4 * 2 / 2.0
52 - 4 * 2 / 2.0
52 - 4 * 1.0
52 - 4.0
48.0
Left -> Right. BODMAS (Bracket Of Division Multiplication) rule is followed while evaluating expression.>>> a, b = 12, 23 # Multiple declartion
>>> print(a, b)
(12, 23)
>>> b, a = a, b
>>> print a, b
23 12
a = 23 creates a new variable, no need to mention value type.bracket while evaluating expression unless explict perference is needed.int.
In [3]:
author = 'Kracekumar'
one_liner_about_python = "Python is simple and powerful language"
description = """Python is a general purpose, high level language.
It is dynamically typed and interpretered language.
"""
print(author)
print(one_liner_about_python)
print(description)
complete_msg = """Author: {}
One liner about Python:
- {}
Long Description:
{}""".format(author, one_liner_about_python, description)
print(complete_msg)
In [6]:
print("lower".upper())
print("upper".lower())
print("captialize".capitalize())
print(" extra spaces ".strip()) # Very useful in web development while cleaning user input
print("find a word's position in the sentence".find('word')) # returns starting position
print("how many times the letter `e` is present in the sentence".count('e'))
print("Replace delete with remove".replace('delete', 'remove'))
print("Python is simple and powerful language".startswith('Python'))
In [10]:
language = 'python'
# Print first character
print(language[0])
# print last character
print(language[-1])
# Find length f the string
print(len(language)) # builtin function
# Print first 3 characters
print(language[0:2]) # Slicing `0` is starting index and `2` is last index
# print last three characters
print(language[-3:])
# Add a dot after python
language = language + "." # Here new variable is created
print(language)
string is immutable datatype.string has lot of useful methods for data processing.negative index can be used for accessing the string content from reverse direction.slicing is used for getting partial content from the string.
In [12]:
print(23 == 32)
print(23 != 32)
print(True == False)
print(True != False)
In [15]:
print(True and False)
print(23 and 12) # Watch for output
print(True or False)
print(23 or 12) # Watch for output
print("python" or "javascript")
print("python" and "javascript")
print(not 23)
In [35]:
collection = ['Python', 23, 45.9, True] # Collection of different elements.
"""Representaion of list
---------------------------
|'python'| 23 | 45.9 | True|
---------------------------
0 1 2 3
"""
print(collection)
# Access the first element
print(collection[0])
# Access the last element
print(collection[-1])
# Replace the first element
collection[0] = 'Go'
print(collection[0])
# Add an element at the last position
collection.append("last")
print(collection[-1])
# Insert an element at position 2
print(collection)
collection.insert(2, 12)
print(collection)
# Delete the last element
del collection[-1]
print(collection)
# Length of the list
print(len(collection))
In [65]:
nested_collection = [['apple', 'orange'], ['Python', 'Go']]
print(nested_collection) # Access first element in first list
print(nested_collection[0][0])
In [23]:
collection = ['Python', 23, 45.9, True]
print(collection.count(23))
print(collection.index(23)) # If not found Exception will be raised.
print('23' in collection) # Check if an element is present in list
print('p' in 'python') # `in` works on strings, list etc..
In [29]:
for i in ['Python', 23, 45.9, True]: # During every iteration i value is replaced, `python` -> `23` -> `45.9` -> `True`
print(i)
In [25]:
for ch in "Python":
print(ch)
In [26]:
for number in range(0, 10): # Produces list of numbers starting from 0 til 9, 10 is excluded.
if number % 2 == 0:
print("Even")
else:
print("Odd")
In [30]:
def square(x): # No need to specify type of the argument.
return x * x
def cube(x):
return square(x) * x
def msg(): # Function with no arguments and doesn't return any value
print("End")
print(square(2))
print(square(23))
msg()
In [32]:
def square(x=2): # if x didn't receive any value, 2 is taken.
return x * x
print(square(23))
print(square(2))
In [66]:
def fxy(f, x, y): # f(x, y) = f(x) . f(y)
return f(x) * f(y)
def square(x):
return x * x
print(fxy(square, 2, 3))
In [44]:
print(sum([1, 2, 3, 4])) # 10
print(max([1, 2, 3, 4])) # 4
print(min([1, 2, 3, 4])) # 1
print(sorted([1, 2, 3, 4])) # Ascending order
print(sorted([1, 2, 3, 4], reverse=True)) # Descending order
print(float(23)) # Typecast into float
print(list("23")) # String -> list
print(str(23))
print(int('23'))
# Find data type
print(type(23))
print(type([2]))
print(type('23'))
In [61]:
class Person:
def __init__(self, first_name, last_name='', age=18): # self is always first argument in all instance method
# __init__ is initializer
self.first_name = first_name
# Instance attribute like instance method self. notation is used inside class to assign value
self.last_name = last_name
self.__age = age # Private like attribute
def full_name(self):
# Instance method
return self.first_name + ' ' + self.last_name
def get_age(self):
# Since __age is private like variable we need to have getters and setters. Getter
return self.__age
def set_age(self, age):
# Setter
self.__age = age
def is_major(self):
return self.__age >= 18
guido = Person("Guido", "van rossum", 58) # __init__ of Person is called
krace = Person("Kracekumar", "Ramaraju", 24)
# Access instance first_name, last_name
print(guido.first_name)
print(guido.last_name)
print(krace.first_name)
print(krace.last_name)
# Access instance methods
print(guido.full_name()) # self is passed implicitly in the background.
print(krace.is_major())
# Modif the age, first_name
krace.set_age(12)
krace.first_name = 'kracekumar'
print(krace.get_age(), krace.first_name)
print(krace.is_major())
In [54]:
months = {'jan': 31, 'feb': 28, 'mar': 31, 'apr': 30} # Colon is used to separate key and value
# `jan` is key and `31` is value
""" Visual representation of Dictionary
-----------
|Key|Value|
-----------
|jan|31 |
-----------
|feb|28 |
-----------
|mar|31 |
-----------
|apr|30 |
-----------
"""
print(months) # Dictionary don't maintain the order of insertion.
print(months['jan']) # Values in dictionary are accessed using key, in list index is used.
print(months.get('jan')) # .get returns None if the key is missing
print('dec' in months) # `in` is used to check presence of key in dictionary.
print(len(months)) # len function is used to find total key, value pair in dictionary.
for key, value in months.items(): # .items() returns two values during every iteration. First is key, second is value
print(key, '->', value)
months['feb'] = 29 # Leap year! if key is already present value will be replaced else key, value pair will be added.
print(months)
months['dec'] = 31
print(months)
In [56]:
l = [1, 2, 3]
print(l[5]) # This raises IndexError since list only contains 3 elements.
In [57]:
d = {'a': 1}
print(d['b']) # Raises KeyError
In [64]:
try:
l = [1, 2, 3]
print(l[5])
except IndexError as e:
print(e)
In [59]:
try:
d = {'a': 1}
print(d['b'])
except KeyError as e:
print(e)
In [62]:
#### 10.4 Catch all
try:
l = [1, 3, 3]
d = {'a': 1}
print(l[5], d['a'])
except (IndexError, KeyError) as e:
print(e)
finally:
print("end")
In [ ]: